package com.jielihaofeng.cachekit;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Johnnie Wind
 * @description 方法的附着体原来是Printer，现在变成事件队列
 * @date 2021/10/25 11:51
 */
public class EventQueue {

    // 线程前缀
    private static final String THREAD_PREFIX = "EventQueue ";
    // 是否销毁
    private boolean destroyed = false;
    // 阻塞队列
    private LinkedBlockingQueue<Runnable> queue;
    // 线程池执行器
    private ThreadPoolExecutor queueProcessor;

    public EventQueue() {
        queue = new LinkedBlockingQueue<>();
        queueProcessor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, queue, new EventThreadFactory(THREAD_PREFIX));
    }

    public void addEventRunner(EventRunner runner) {
        if (!destroyed) {
            runner.run();
        }
    }

    public void dispose() {
        if (!destroyed) {
            destroyed = true;

            queueProcessor.shutdown();
            queueProcessor = null;
        }
    }
}
